package com.fsnbigdata.web;

import com.fsnbigdata.domain.ZhExpert;
import com.fsnbigdata.domain.ZhKopp;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.service.api.ZhExpertService;
import com.fsnbigdata.util.ReflectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: chen quan zhou
 * @Date: Created in 19:13 2018/9/29
 * @Modified By:
 */

@RooController(entity = ZhExpert.class, pathPrefix = "/api", type = ControllerType.COLLECTION)
@RooJSON
@RestController
@RequestMapping(value = "/api/zhexpert", name = "ZhExpertController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "ZhExpert", description = "专家咨询")
public class ZhExpertController {
    
    @Autowired
    private ZhExpertService zhExpertService;
    
    /**
     * 根据id查询数据
     *
     * @param request
     * @return
     */
    @GetMapping(value = "findOne")
    public ZhExpert findById(HttpServletRequest request) {
        String id = request.getParameter("id");
        return zhExpertService.findById(Long.parseLong(id));
    }
    
    /**
     * 新增数据
     *
     * @param zhExpert
     * @param result
     * @return
     */
    @PostMapping(value = "save")
    @PreAuthorize("hasRole('DB_ZHEXPERT')")
    @ApiOperation(value = "",notes = "save")
    public ResponseEntity<?> save(@Valid @RequestBody ZhExpert zhExpert, BindingResult result ,Principal principal) throws Exception {
        if (zhExpert.getId() != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }
        zhExpert.setAdd_time(new Date());
        zhExpert.setCreator(principal.getName());
        ZhExpert newZhExpert = zhExpertService.save(zhExpert);

        Class<?> clazz = ZhExpertController.class;
        Method method = clazz.getMethod("save", ReflectUtil.getPeremeterClass(clazz, "save"));
        ReflectUtil.setAnnotationOn(method,"新增专家咨询，姓名："+newZhExpert.getName());

        return ResponseEntity.ok(newZhExpert);
    }
    
    /**
     * 更新数据
     *
     * @param zhExpert
     * @param result
     * @return
     */
    @PutMapping(value = "update")
    @PreAuthorize("hasRole('DB_ZHEXPERT')")
    @ApiOperation(value = "",notes = "update")
    public ResponseEntity<?> update(@Valid @RequestBody ZhExpert zhExpert, BindingResult result, Principal principal) throws Exception {
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }
        String name =  zhExpertService.findById( zhExpert.getId()).getName();
        zhExpert.setCreator(principal.getName());
        ZhExpert newZhExpert = zhExpertService.update(zhExpert);
        Class<?> clazz = ZhExpertController.class;
        Method method = clazz.getMethod("update", ReflectUtil.getPeremeterClass(clazz, "update"));
        ReflectUtil.setAnnotationOn(method,"更新专家咨询，姓名："+name);
        return ResponseEntity.ok(newZhExpert);
    }
    
    /**
     * 返回所有列表数据
     *
     * @return
     */
    @GetMapping(value = "list")
    @PreAuthorize("hasRole('DB_ZHEXPERT')")
    public List<ZhExpert> findAll(Authentication authentication) {
        List<String> authorities = authentication.getAuthorities().stream().map(it -> it.getAuthority()).collect(Collectors.toList());
        String creator="";
        if(!authorities.contains("ROLE_USER_ADMIN")){
            creator = authentication.getName();
        }
        return zhExpertService.findAll(creator);
    }
    
    /**
     * 删除一条记录
     *
     * @param zhExpert
     * @return
     */
    @DeleteMapping(name = "delete", value = "delete")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "", paramType = "path", dataType = "int", required = true)
    })
    @PreAuthorize("hasRole('DB_ZHEXPERT')")
    @ApiOperation(value = "",notes = "delete")
    public ResponseEntity<?> delete(@ModelAttribute ZhExpert zhExpert) throws Exception {
        String name = zhExpertService.findById(zhExpert.getId()).getName();
        zhExpertService.deleteOne(zhExpert.getId());

        Class<?> clazz = ZhExpertController.class;
        Method method = clazz.getMethod("delete", ReflectUtil.getPeremeterClass(clazz, "delete"));
        ReflectUtil.setAnnotationOn(method,"删除专家咨询，姓名："+name);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 删除多条记录
     *
     * @param ids
     * @return
     */
    @DeleteMapping(name = "deleteMany", value = "deleteMany")
    @PreAuthorize("hasRole('DB_ZHEXPERT')")
    public ResponseEntity<?> deleteMany(@PathVariable("ids") Collection<Long> ids) {
        zhExpertService.delete(ids);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 根据姓名进行搜索
     *
     * @param request
     * @param name
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "advanceSearch")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public Page<ZhExpert> getList(HttpServletRequest request, @RequestParam(required = false) String name, Pageable pageable) {
        return zhExpertService.findByPageAndSize(name, pageable);
    }
    
    /**
     * 根据类型查询数据
     *
     * @param type
     * @return
     */
    @GetMapping(value = "findAllByType")
    public List<ZhExpert> findByType(Integer type) {
        return zhExpertService.findAllByType(type);
    }

    @GetMapping(name = "search", value = "queryList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public List queryList(HttpServletRequest request,Pageable pageable){
        return zhExpertService.queryList(request.getParameter( "type" ),pageable);
    }
    
}
